<template>
  <div class="dialog">
    <el-dialog :title="'出鱼任务' + title" :visible.sync="showDialog" width="80%" top="0" :close-on-click-modal="false"
      @close="cancel">
      <el-form ref="ruleForm" label-position="left" :model="formData" :rules="rules" class="el-form">
        <el-form-item label="任务名称：" class="w50p" prop="fishOutTaskName">
          <el-input :disabled="formData.auditType == 'PASS'" v-model="formData.fishOutTaskName" clearable
            placeholder="请输入出鱼任务名称" />
        </el-form-item>
        <el-form-item label="创建人" class="w50p" prop="staffId">
          <el-select filterable clearable disabled v-model="formData.staffId" placeholder="请选择"  @change="staffChange">
            <el-option v-for="(item, index) in staffList" :label="item.staffName" :value="item.staffId"
              :key="index + 'staff'" />
          </el-select>
        </el-form-item>
        <!-- codeNumber -->
        <el-form-item label="产出码单号" class="w100p" prop="note">
          <el-input v-model="formData.codeNumber" autosize clearable placeholder="请输入产出码单号" />
        </el-form-item>
        <!-- <el-form-item label="备注" class="w100p" prop="note">
          <el-input v-model="formData.note" type="textarea" autosize clearable placeholder="请输入备注" />
        </el-form-item> -->
        <el-row :gutter="15">
          <el-table ref="rightTableData" :data="formData.fishOutTaskDetailList" tooltip-effect="dark"
            highlight-current-row border stripe :row-style="{ height: '80px' }" class="rightTableData">
            <el-table-column type="index" label="序号" width="50" />
            <el-table-column label="出鱼类型" align="center" min-width="90">
              <template slot-scope="scope">
                <el-form-item :prop="'fishOutTaskDetailList.' + scope.$index + '.fishType'" class="w100p"
                  :rules="{ required: true, message: '鱼类型不能为空', trigger: ['change', 'blur'] }">
                  <el-select filterable clearable v-model="scope.row.fishType" >
                    <el-option v-for="(item, index) of fishType" :key="index + 'fishType'" :label="item.value"
                      :value="item.name" />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="鱼品种" prop="fishVarietyId" align="center" min-width="90">
              <template slot-scope="scope">
                <el-form-item :prop="'fishOutTaskDetailList.' + scope.$index + '.fishVarietyId'" class="w100p"
                  :rules="{ required: true, message: '鱼品种不能为空', trigger: ['change', 'blur'] }">
                  <el-select filterable clearable v-model="scope.row.fishVarietyId"  @change="querySpecification">
                    <el-option v-for="(item, index) of varietyList" :key="index + 'variety'" :label="item.varietyName"
                      :value="item.fishVarietyId" />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="出鱼规格(斤)" prop="specificationId" align="center" min-width="90">
              <template slot-scope="scope">
                <el-form-item :prop="'fishOutTaskDetailList.' + scope.$index + '.specificationId'" class="w100p"
                  :rules="{ required: true, message: '鱼规格不能为空', trigger: ['change', 'blur'] }">
                  <el-select filterable clearable v-model="scope.row.specificationId"  placeholder="请先选择品种">
                    <el-option v-for="(item, index) of specificationList" :key="index + 'specification'"
                      :label="item.specificationName" :value="item.specificationId" />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="产出数量" prop="num" min-width="100">
              <template slot-scope="scope">
                <el-form-item :prop="'fishOutTaskDetailList.' + scope.$index + '.num'" class="w100p"
                  :rules="{ required: true, message: '数量不能为空', trigger: 'blur' }">
                  <el-input v-model="scope.row.num" min="0" type="number"
                    @change="scope.row.num <= 0 ? scope.row.num = '' : ''">
                    <template slot="append">尾</template>
                  </el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="产出重量" prop="weight" min-width="100">
              <template slot-scope="scope">
                <el-form-item :prop="'fishOutTaskDetailList.' + scope.$index + '.weight'" class="w100p"
                  :rules="{ required: true, message: '重量不能为空', trigger: 'blur' }">
                  <el-input v-model="scope.row.weight" min="0" type="number"
                    @change="scope.row.weight <= 0 ? scope.row.weight = '' : ''">
                    <template slot="append">斤</template>
                  </el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="备注" min-width="100">
              <template slot-scope="scope">
                <el-form-item :prop="'fishOutTaskDetailList.' + scope.$index + '.remark'" class="w100p">
                  <el-input v-model="scope.row.remark"></el-input>
                </el-form-item>
              </template>
              <!-- remark -->
            </el-table-column>
            <el-table-column label="操作" min-width="80">
              <template slot-scope="scope">
                <el-button v-if="nowChanceStau === 'edit'" type="text" style="color:red;text-decoration: underline;"
                  size="small" @click.native.prevent="editRow(scope.row, scope.$index)">{{ scope.row.fishOutTaskDetailId ?
                    '修改' : '添加' }}</el-button>
                <el-button v-if="nowChanceStau === 'edit' && !scope.row.fishOutTaskDetailId" type="text"
                  style="color:red;text-decoration: underline;" size="small"
                  :disabled="formData.fishOutTaskDetailList.length <= 1"
                  @click.native.prevent="deleteRow(scope.$index)">删除</el-button>
                <el-button v-if="nowChanceStau === 'add'" type="text" style="color:red;text-decoration: underline;"
                  size="small" :disabled="formData.fishOutTaskDetailList.length <= 1"
                  @click.native.prevent="deleteRow(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
            <template slot="empty">
              <div>请添加数据</div>
            </template>
          </el-table>
        </el-row>
        <el-row :gutter="15">
          <el-button type="info" plain icon="el-icon-circle-plus-outline" class="addInfo"
            @click="addButInfo">添加</el-button>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="cancelbtn" @click="cancel()">取 消</el-button>
        <el-button type="primary" class="savebtn" @click="save('ruleForm')">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { dialogMixin } from "@/utils/dialogMixin";
import FishOutTaskApi from "@/api/output-manage/fish-out-task";
import SpecificationApi from "@/api/basic-info-manage/specification";
import FishVarietyApi from "@/api/basic-info-manage/fishVariety";
import StaffApi from "@/api/basic-info-manage/staff";
import EnumApi from "@/api/enum";
export default {
  name: '',
  components: {},
  mixins: [dialogMixin],
  props: {
    // 弹框名称
    titleText: {
      type: String,
      default: ""
    },
    nowChanceStau: {
      type: String,
      default: ""
    },
    show: {
      type: Boolean,
      default: false
    },
    editObject: {
      type: [Object],
      default: () => {
        return {}
      }
    },
  },
  data () {
    return {
      title: '',
      formData: {},
      rightTableData: [],
      fishType: [],
      staffList: [],
      specificationList: [],
      varietyList: [],
      rules: {
        staffId: [
          { required: true, message: "请选择创建人", trigger: ["change", "blur"] }
        ],
        fishOutTaskName: [
          { required: true, message: "请输入任务名称", trigger: ["change", "blur"] }
        ],
      },
      showDialog: this.show
    };
  },

  watch: {
    show (v) {
      this.showDialog = v;
      this.$refs['ruleForm'] && this.$refs['ruleForm'].clearValidate()
    },
    editObject (v) {
      // this.formData = v;
    },
    nowChanceStau (v) {
      this.title = this.titleText
      if (v === "add") {
        this.$nextTick(() => {
          let staffName = sessionStorage.getItem("staffName")
          let staffId = sessionStorage.getItem("staffId")
          let userList = this.staffList.filter(item => {
            return Number(item.staffId) === Number(staffId)
          })
          this.formData = {
            staffName: userList.length == 0 ? this.staffList[0].staffName : staffName,
            staffId: userList.length == 0 ? this.staffList[0].staffId : Number(staffId),
            fishOutTaskDetailList: [{}]
          };
          this.$refs['ruleForm'].resetFields()
        })
      }
      if (v === "edit") {
        this.formData = this.editObject;
        console.log(this.editObject)
        this.title = this.formData.auditType == 'PASS' ? '变更' : this.titleText
        this.queryfishOutTaskDetail(this.editObject.fishOutTaskId)
        SpecificationApi.queryByCondition({}).then(res => {
          this.specificationList = res.data
        })
      }
    }
  },
  created () {
  },
  mounted () {
    this.queryStaff()
    // this.querySpecification()
    this.queryFishVariety()
    this.queryEnum()
  },
  methods: {
    queryfishOutTaskDetail (e) {
      FishOutTaskApi.queryDetail({ fishOutTaskId: e }).then(res => {
        this.formData.fishOutTaskDetailList = res.data
      })
    },
    queryStaff () {
      StaffApi.queryByCondition().then(res => {
        this.staffList = res.data
      })
    },
    queryFishVariety () {
      FishVarietyApi.getCurrentVarietyList().then(res => {
        this.varietyList = res.data
      })
    },
    queryEnum () {
      EnumApi.list({ enumType: 'FishType' }).then(res => {
        this.fishType = res.data
        this.fishType.find((item, index) => {
          if (item.name === 'DEAD_FISH') {
            this.fishType.splice(index, 1)
            return true
          }
        })
      })
    },
    staffChange (e) {
      console.log(e)
      this.staffList.find((item) => {
        if (item.staffId == e) {
          this.formData.staffName = item.staffName
          console.log(item.staffName)
          return true
        }
      })
    },
    querySpecification (e) {
      const params = {}
      if (e) params.fishVarietyId = e
      SpecificationApi.queryByCondition(params).then(res => {
        this.specificationList = res.data
      })
    },
    // 修改/新增一行数据
    editRow (rows, index) {
      const valiSome = ['fishOutTaskDetailList.' + index + '.fishType',
      'fishOutTaskDetailList.' + index + '.fishVarietyId',
      'fishOutTaskDetailList.' + index + '.specificationId',
      'fishOutTaskDetailList.' + index + '.num',
      'fishOutTaskDetailList.' + index + '.weight',
      'fishOutTaskDetailList.' + index + '.remark'
      ]

      this.$refs['ruleForm'].validateField(valiSome);// 校验当前修改/添加行

      if (rows.fishOutTaskDetailId) {
        let params = {
          fishOutTaskDetailId: rows.fishOutTaskDetailId,
          fishType: rows.fishType,
          fishVarietyId: rows.fishVarietyId,
          specificationId: rows.specificationId,
          num: rows.num,
          weight: rows.weight,
          remark: rows.remark || ''
        }
        FishOutTaskApi.editDetail(params).then(res => {
          if (res.success === true) {
            this.$message.success("修改成功！");
          } else {
            this.$message.error(res.message);
          }
        })
      } else {
        let params = {
          fishOutTaskId: this.editObject.fishOutTaskId,
          fishType: rows.fishType,
          fishVarietyId: rows.fishVarietyId,
          specificationId: rows.specificationId,
          num: rows.num,
          weight: rows.weight,
        }
        FishOutTaskApi.addDetail(params).then(res => {
          if (res.success === true) {
            this.queryfishOutTaskDetail(this.editObject.fishOutTaskId);
            this.$message.success("添加成功！");
          } else {
            this.$message.error(res.message);
          }
        })
      }
    },
    // 点击添加按按钮
    addButInfo () {
      let list = {};
      this.formData.fishOutTaskDetailList.unshift(list);
    },
    // 删除改行
    deleteRow (index) {
      this.formData.fishOutTaskDetailList.splice(index, 1);
    },
    save (formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          let params = {
            ...this.formData
          }
          if (this.nowChanceStau == 'add') {
            FishOutTaskApi.add({params,auditType:'REVIEW'}).then(res => {
              if (res.success) {
                this.$message.success("处理成功");
                this.close()
              } else {
                this.$message.error(res.message);
              }
            });
          } else if (this.nowChanceStau == 'edit') {
            FishOutTaskApi.edit(params).then(res => { 
              if (res.success) {
                this.$message.success("处理成功");
                this.close()
              } else {
                this.$message.error(res.message);
              }
            });
          }

        } else {
          return false;
        }
      });
    },
    close () {
      this.$emit("closeDialog");
    },
    cancel () {
      this.$emit("cancelDialog");
    }
  }
};
</script>

<style lang="scss" scoped>
.rightTableData {
  ::v-deep .el-form-item__error {
    top: calc(100% - 5px);
  }

  ::v-deep .el-form-item {
    height: 40px;
    margin-bottom: 0;

    .el-input__inner {
      height: 40px;
    }
  }

  ::v-deep .cell {
    overflow: visible;
  }

  // ::v-deep .el-input__inner{

  // }
}

.addInfo {
  width: 100%;
}

::v-deep .el-table {
  position: relative;
}
</style>
